package enterprisePerson

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type DeleteEnterprisePersonByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewDeleteEnterprisePersonByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *DeleteEnterprisePersonByIdApiLogic {
	hostname, _ := os.Hostname()
	return &DeleteEnterprisePersonByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *DeleteEnterprisePersonByIdApiLogic) DeleteEnterprisePersonByIdApi(req *types.IdReq) (resp string, err error) {
	// todo: add your logic here and delete this line
	personEntity, err := dao.EnterprisePersonEntity.WithContext(l.ctx).Where(dao.EnterprisePersonEntity.ID.Eq(req.Id)).First()
	switch {
	case errors.Is(err, gorm.ErrRecordNotFound):
		return "", err
	case err != nil:
		return "", err
	default:
		tx := dao.Use(l.svcCtx.MysqlDb).Begin()
		// 1、删除账号
		if _, err = tx.AccountEntity.WithContext(l.ctx).Where(
			dao.AccountEntity.AccountType.Eq(enum.EnterprisePersonEnum),
			dao.AccountEntity.EnterpriseID.Eq(personEntity.EnterpriseID),
			dao.AccountEntity.PersonID.Eq(personEntity.ID),
		).Delete(); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("删除失败")
		}
		// 2.删除信息
		if _, err = tx.EnterprisePersonEntity.WithContext(l.ctx).Where(dao.EnterprisePersonEntity.ID.Eq(req.Id)).Delete(); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("删除失败")
		}
		if err = tx.Commit(); err != nil {
			return "", errors.New("删除失败")
		}
	}
	return "操作成功", nil
}
